Say it ain't so – the “If-Not†conditional
<p>Suppose, in a grandfather clock, we want to implement a chime for all hours except the 00:00 hrs and 12:00 hrs, for which there is a long ring.</p> <p>Normally, we would check for each hourly time that is not a 12-hourly event, and for each comparison we would do the necessary sound effects. Or, if we are smart, combine all such comparison expressions with the logical OR operator (“||â€) and do the check in just a single “if clause.†The pseudo-code would look something like this:</p> <p>if (time == “01:00hrs†|| time==â€02:00hrs†|| … || time ==â€23:00hrs){ </p> <p>trace(“C*HIME†+ time); </p> <p>}else{</p> <p>trace(“Long-Ring†+ time); </p> <p>}</p> <p>Clearly, this approach will not serve us well, since we would have to connect together 22</p> <p>ED: Commonly, spell out numbers under ten only. </p> <p>expressions in one conditional using OR operators. </p> <p>Recall that any conditional evaluates to a Boolean value. If the condition evaluates to true, then its COMPLEMENT evaluates to false, and vice-versa. What we need is a new operator: the NOT operator which is simply an exclamation point: !In the above example, if we want to check that the time is NOT '00:00', you'd simple write: if (!(time == “00:00â€)) … See how easy that is?</p> <p>With a little thought, we can do the entire problem that way. Restructuring the above pseudo-code, we can write the following logical equivalent: </p> <p>if (! (time == “00:00hrs†|| time == “12:00hrs)) { //if time is NOT 00:00 or 12:00</p> <p>trace(“Chime†+ time); </p> <p>}else {</p> <p>trace(“Long-Ring†+ time); </p> <p>}</p> <p>Of course, the above code could be rearranged (mainly, the order of the if-else clauses) as:</p> <p>if (time == “00:00hrs†|| time == “12:00hrsâ€){ </p> <p>trace(“Long-Ring†+ time); </p> <p>}else { </p> <p>trace(“Chime†+ time); </p> <p>}</p> <p>Notice that when we turned a negative check to a positive check, the bodies of the if and else blocks were exchanged…the call to chime() went to the new else-clause, and the call to long-ring() went to the new if-clause. That is how Boolean logic works!</p>